/**
 * 功能权限
 */
var viewflag = true;
mini.parse();
var tree = mini.get("treegrid1");
var treegridModualr = mini.get('treegridModualr');
var grid = mini.get("datagrid1");
var roleIds;
var moudlarIdArr = [];			//存放模块id数组(点选时)
var modularDataArr = [];		//存放点选以后的数据组合(菜单和按钮)
var statuss = false;		//勾选是true;(默认是false)
grid.load(ajaxUrl + "/role/list.do");		//角色数据列表加载
grid.load();
var menuColumns = new ColumnsMenu(grid);
mini.get("sp").set({
	height : document.body.clientHeight - 40
});
//修改
function update() {
	mini.get("but_update").disable(); 
	mini.get("but_save").enable();
	mini.get("but_abandon").enable();
	viewflag = false;
	treegridModualr.unmask();
	//tree.unmask();
	grid.mask({
		html : "<div></div>",
		cls : "mini-panel",
		style : "width: 100%; height: 100%;filter:alpha(Opacity=80);-moz-opacity:0.5;opacity: 0.5;"
	});
} 
//放弃
function abandon() {
	
	//数据初始化
	moudlarIdArr = [];		//模块id
	treeDataArr = [];		//保存数据
	localTreeData = [];		//本地存储
	//清空
	treegridModualr.setData([]);
	tree.setData([]);
	//取消遮罩
	grid.unmask();
	//按钮初始化
	//mini.get("but_update").enable();
	mini.get("but_update").disable();
	mini.get("but_save").disable();
	mini.get("but_abandon").disable();
	viewflag = true;
	treegridModualr.mask({
		html : "<div></div>",
		cls : "mini-panel",
		style : "width: 100%; height: 100%;filter:alpha(Opacity=80);-moz-opacity:0.5;opacity: 0.5;"
	});
	tree.mask({
				html : "<div></div>",
				cls : "mini-panel",
				style : "width: 100%; height: 100%;filter:alpha(Opacity=80);-moz-opacity:0.5;opacity: 0.5;"
	});
}

//保存
function save() {
	//模块节点
	var moudlarNodes = treegridModualr.getCheckedNodes(true);		
	//菜单节点
	//var nodes = tree.getCheckedNodes(true);	
	var nodes = [];
	treeDataArr.forEach((item,index)=>{
		for(k in item){
			item[k].forEach((itemChild,index)=>{
				nodes.push(itemChild);
			})
		}
	})
	console.log(nodes,'保存时候的数据');
	var funbtnArr = [];		//有按钮	
	var noBtnArr = [];		//无按钮
	//遍历node
	nodes.forEach((item,index)=>{
		if(item.functions){
			funbtnArr.push(item);
		}else{
			noBtnArr.push(item);
		}
	});
	var haveBtnMenus =  [];
	var noBtnMenus = [];
	//遍历按钮都有哪些
	funbtnArr.forEach((item,index)=>{
		var haveBtnObj = {};
		haveBtnObj.modularId = item.modularId;
		haveBtnObj.menuId = item.id.split('_')[1];
		haveBtnObj.roleId = roleIds;
		var actionArr = [];
		item.functions.forEach((btnTrue,index)=>{
			if(btnTrue.checked){
				actionArr.push(btnTrue.action);
			}
		});
		actionArr = actionArr.join();
		haveBtnObj.buts = actionArr;
		haveBtnMenus.push(haveBtnObj);
	});
	console.log(haveBtnMenus,'有按钮的');
	//遍历无按钮的菜单
	noBtnArr.forEach((item,index)=>{
	 	var noBtnObj = {};
		noBtnObj.modularId = item.modularId;
		noBtnObj.menuId = item.id.split('_')[1];
		noBtnObj.roleId = roleIds;
		noBtnObj.buts = '';
		noBtnMenus.push(noBtnObj);
	});
	console.log(noBtnMenus,'无按钮的');
	var dataArr = [];
	haveBtnMenus.forEach((item,index)=>{
		dataArr.push(item);
	});
	noBtnMenus.forEach((item,index)=>{
		dataArr.push(item);
	});
	moArr.forEach((item,index)=>{
		dataArr.push(item);
	});
	console.log(dataArr,'最后输出的');
	
	
	
	
	
	
	
	
	
	
	
//	//保存
//	var values = new Array();			//有按钮菜单数组
//	var modeularArr = new Array();		//模块数组
//	var menuArr = new Array();			//无按钮菜单数组
//	var dataArr = new Array();			//最后传的数组
//	//遍历树中被选中的每一行(菜单行/模块行)
//	for(var  i = 0; i < nodes.length; i++){
//		//模块
//		if(nodes[i].id.substring(0,2) == "mo"){
//			modeularArr.push(nodes[i]);
//		//菜单
//		}else if(nodes[i].id.substring(0,2) == "mu"){
//			//菜单数组
//			if(nodes[i].functions){
//				var fBtns = nodes[i].functions;
//				for(var j = 0; j < fBtns.length; j++){
//					//button被选中的菜单
//					if(fBtns[j].checked){
//						values.push(nodes[i]);
//					}else{
//						menuArr.push(nodes[i]);
//					}
//				}
//			//button未被选中的菜单
//			}else{
//				menuArr.push(nodes[i]);
//			}
//		}
//
//	}
//	//被勾选按钮菜单(菜单)
//	var selects = uniq(values);
//	for(var k = 0; k < selects.length; k++) {
//		var menuObj = {};
//		menuObj.roleId = grid.getSelected().roleId;
//		menuObj.modularId = selects[k].modularId
//		menuObj.menuId = selects[k].id.split("_")[1];
//		var buts = selects[k].functions;
//		var butsid = "";
//		for (var x = 0; x < buts.length; x++) {
//			if (buts[x].checked) {
//				butsid += buts[x].action + ",";
//			}
//		}
//		menuObj.buts = butsid.substring(0, butsid.length - 1);
//		dataArr.push(menuObj);
//	}
//	console.log(dataArr,'有按钮的菜单-——--');
//	//未被勾选按钮菜单
//	var menuNotBtn = uniq(menuArr);
//	for(var k = 0; k < menuNotBtn.length; k++) {
//		var menuNotObj = {};
//		menuNotObj.roleId = grid.getSelected().roleId;
//		menuNotObj.modularId = menuNotBtn[k].modularId
//		menuNotObj.menuId = menuNotBtn[k].id.split("_")[1];
//		menuNotObj.buts = "";
//		dataArr.push(menuNotObj);
//	}
//	console.log(menuNotObj,'没有按钮的菜单----');
//	//模块
//	for(var m = 0; m < modeularArr.length; m++){
//		var modularObj = {};
//		modularObj.roleId = grid.getSelected().roleId;
//		if(modeularArr[0].id.substring(0,2) == "mo"){
//			modularObj.modularId = modeularArr[m].modularId ? modeularArr[m].modularId : modeularArr[m].id.split("_")[1];
//		}
//		modularObj.menuId = "";
//		modularObj.buts = "";
//		dataArr.push(modularObj);
//	}
	
	//原始的
	//for (var i = 0; i < nodes.length; i++) {
	//	var pnodes = tree.getAncestors(nodes[i]);
	//	for (var n = 0; n < pnodes.length; n++) {
	//		var obj = {};
	//		//得到节点层级（number）
	//		if (tree.getLevel(pnodes[n]) == 0) {
	//			obj.roleId = grid.getSelected().roleId;
	//			obj.modularId = pnodes[n].id.split("_")[1];
	//			obj.menuId = nodes[i].id.split("_")[1];
	//			var buts = nodes[i].functions;
	//			var butsid = "";
	//			for (var x = 0; x < buts.length; x++) {
	//				if (buts[x].checked) {
	//					butsid += buts[x].action + ",";
	//				}
	//			}
	//			obj.buts = butsid.substring(0, butsid.length - 1);
	//			continue;
	//		}
	//		values.push(obj);
	//	}
	//}
//	moudlarIdArr.forEach((item,index)=>{
//		if(index < moudlarIdArr.length){
//			if(moudlarIdArr[index].menuId == moudlarIdArr[index+1].menuId){
//				console.log(moudlarIdArr[index],'相同的');
//			}
//		}
//	})
	
	moudlarIdArr = moudlarIdArr.join();
	var paramsObjNew = {
		roleId: grid.getSelected().roleId,
		Modularids: moudlarIdArr,
		data: mini.encode(dataArr)
	}
	console.log(paramsObjNew,'最后保存时的数据');
//	var paramsObj = {
//		data: mini.encode(dataArr)
//	}
	//保存请求
	$.ajax({
		url     : ajaxUrl + "/roleMath/saveRoleMath.do",
		type    : "POST",
		async   : false,
		data    : paramsObjNew,
		success : function (data){
			abandon();
		},
		error:function(data){
			mini.alert(data);
		}
	});
}
function resize() {
	if (viewflag) {
		tree.mask({
			html : "<div></div>",
			cls : "mini-panel",
			style : "width: 100%; height: 100%;filter:alpha(Opacity=80);-moz-opacity:0.5;opacity: 0.5;"
		});
	}
}
//数据表选择(选择用户得到模块)
function onSelectionChanged(e) {
	//修改按钮禁用取消
	mini.get("but_update").enable(); 
	var id = e.selected.roleId;
	roleIds = id;
	treegridModualr.load(ajaxUrl + "/roleMath/findModularAllAuth.do?roleId=" + id);
	// console.log(JSON.stringify(tree.getData()));
	if (viewflag) {
		treegridModualr
			.mask({
				html : "<div></div>",
				cls : "mini-panel",
				style : "width: 100%; height: 100%;filter:alpha(Opacity=80);-moz-opacity:0.5;opacity: 0.5;"
			});
	}
}
var treeDataArr = [];		//存放修改过的数据(用来保存)
var selectNodeArr = [];
var localTreeData = [];		//本地数据（用来赋值）
//通过模块选择菜单
function onNodeselectMo(e) {
/*	treegridModualr.mask({
		html : "<div></div>",
		cls : "mini-panel",
		style : "width: 100%; height: 100%;filter:alpha(Opacity=80);-moz-opacity:0.5;opacity: 0.5;"
	});*/
	//将选中的模块ID存起来
	var modularId = e.selected.id.split('_');
	modularId = modularId[1];
	//判断当前节点是否被选中
	var boolean = tree.isCheckedNode(e.node);
	var moTreeLesf = {};
	//如果被选中，那么填进去
	if(boolean){
		/*if(moArr.indexOf(modularId) == -1){
			console.log("已经点击过，不需要新增");
		}else{*/
			moTreeLesf.modularId = modularId;
			moTreeLesf.roleId = roleIds;
			moTreeLesf.menuId = '';
			moTreeLesf.buts = '';
			moArr.push(moTreeLesf);
		//}
	}
	console.log(moArr);
	//判断数组中是否有该模块id，判断是否从后台取数据
	//判断被点中的模块id是否是已经点击过的(本地赋值)
	if(moudlarIdArr.indexOf(modularId) == -1){
		moudlarIdArr.push(modularId);
		tree.load(ajaxUrl + "/roleMath/findMenusAuthByRoleId.do?roleId=" + roleIds + "&ModularId=" + modularId);
		//勾选模块时加载数据
		var treeDatas = tree.getData();
		console.log(treeDatas,'第一次加载的数据');
		if(treeDatas.length > 0){
			treegridModualr.unmask();
		}
//		//取消遮罩
//		if(treeDatas.length > 0){
//			treegridModualr.unmask();
//		}else{
//			
//		}
		var  meObj = {}; 		//保存
		var localObj = {};		//赋值
		if(treeDatas.length > 0){
			//存到本地用来第二次点击进入的时候赋值用
			localObj['mo' + modularId] = treeDatas;
			localTreeData.push(localObj);
			//保存用
			meObj['mo' + treeDatas[0].modularId] = tree.getCheckedNodes(true);
			treeDataArr.push(meObj);
			console.log(treeDataArr,'所有被点击的数据的集合');
		}else{
			//赋值(无子节点)
			localObj['mo' + modularId] = [];
			localTreeData.push(localObj);
			//保存
			meObj['mo' + modularId] = tree.getCheckedNodes(true);
			treeDataArr.push(meObj);
		}
	}else{
		//遍历数组中的每一项
		treeDataArr.forEach(function(item,index){
			for(var key in item){
				if(key.split('o')[1] == modularId){
					//赋值
					tree.setData(localTreeData[index][key]);
				}
			}
		})
	}
}

var moArr = [];
//勾选模块
function onModularNodeselect(e){
/*	treegridModualr.mask({
		html : "<div></div>",
		cls : "mini-panel",
		style : "width: 100%; height: 100%;filter:alpha(Opacity=80);-moz-opacity:0.5;opacity: 0.5;"
	});*/
	console.log(moudlarIdArr);
	//得到被勾选的模块id
	var modularId = e.node.id.split('_')[1];
	//判断被勾选的模块id在储存的模块id数组中是否存在
	if(moudlarIdArr.indexOf(modularId) == -1){
		moudlarIdArr.push(modularId);
	}else{
		console.log('有');
	}
	console.log(moudlarIdArr,'勾选状态和点击状态都存起来');
	//true：未选中(取消选中)
	if(e.checked){
		moArr.forEach((item,index)=>{
			if(item.modularId == modularId){
				moArr.splice(index,1);
			}
		});
//		console.log(moudlarIdArr,'模块');
//		console.log(moArr,'取消选中');
	}else{
		console.log('勾选');
		console.log(localTreeData,'判断本地数据');
		if(localTreeData.length > 0){
			treegridModualr.unmask();
			localTreeData.forEach((item,index)=>{
				console.log(item,'被勾选的');
				for(k in item){
					if(k.split('o')[1] == modularId){
						tree.setData(localTreeData[index][k]);
					}
				}
			})
		}else{
			tree.load(ajaxUrl + "/roleMath/findMenusAuthByRoleId.do?roleId=" + roleIds + "&ModularId=" + modularId);
			
			//勾选模块时加载数据
			var treeDatas = tree.getData();
			if(treeDatas.length > 0){
				treegridModualr.unmask();
			}
			var  meObj = {}; 		//保存
			var localObj = {};		//赋值
			if(treeDatas.length > 0){
				//存到本地用来第二次点击进入的时候赋值用
				localObj['mo' + modularId] = treeDatas;
				localTreeData.push(localObj);
				//保存用
				meObj['mo' + treeDatas[0].modularId] = tree.getCheckedNodes(true);
				treeDataArr.push(meObj);
				console.log(treeDataArr,'所有被点击的数据的集合');
			}else{
				//赋值(无子节点)
				localObj['mo' + modularId] = [];
				localTreeData.push(localObj);
				//保存
				meObj['mo' + modularId] = tree.getCheckedNodes(true);
				treeDataArr.push(meObj);
			}
			console.log(treeDataArr,'勾选时');
		}
		var treeDatas = tree.getData();
		var nodes = tree.getCheckedNodes(true);
		//执行
		var moObj = {};
		moObj.modularId = modularId;
		moObj.roleId = roleIds;
		moObj.menuId = '';
		moObj.buts = '';
		moArr.push(moObj);
		console.log(moArr,'选中');
	}
}
//节点选择时
var treeMenusDataArr = [];
//选择子节点时（勾选菜单）
function onNodeselect(e) {
	statuss = true;
	console.log(e,'勾选/取消勾选时');
	if(!e.checked){
		console.log('选中了');
		//得到被选中的树节点
		var treeMenusData = tree.getCheckedNodes(true);
		var meObj = {};
		if(treeMenusData.length > 0){
			treeDataArr.forEach((item,index)=>{
				for(var key in item){
					if(key.split('o')[1] == treeMenusData[0].modularId){
						item[key] = treeMenusData;
					}
				}
			})
			console.log(treeDataArr,'被选中的');
		}else{
			console.log('空的');
		}
	}else{
		var noCkeckedNode = e.node;
		//取消勾选，则从保存的data里删除这一条
		treeDataArr.forEach((item,index)=>{
			for(var key in item){
				if(key.split('o')[1] == noCkeckedNode.modularId){
					var itemKey = item[key];
					itemKey.forEach((item,index)=>{
						if(item.id == noCkeckedNode.id){
							itemKey.splice(index,1);
						}
					})
				}
			}
		});
		console.log(treeDataArr,'取消勾选以后的整体数据');
	}
}
//动态绘制按钮
function ondrawcell(e) {
	var tree = e.sender, record = e.record, column = e.column, field = e.field, id = record[tree
			.getIdField()], funs = record.functions;

	function createCheckboxs(funs) {
		if (!funs)
			return "";
		//如果有functions就执行
		var html = "";
		for (var i = 0, l = funs.length; i < l; i++) {
			var fn = funs[i];
			var clickFn = 'checkFunc(\'' + id + '\',\'' + fn.action
					+ '\', this.checked)';
			var checked = fn.checked ? 'checked' : '';
			html += '<label class="function-item"><input onclick="' + clickFn
					+ '" ' + checked + ' type="checkbox" name="' + fn.action
					+ '" hideFocus/>' + fn.name + '</label>';
		}
		return html;
	}

	if (field == 'functions') {
		e.cellHtml = createCheckboxs(funs);
	}
}

function getFuns() {
	var data = tree.getData();
	var json = mini.encode(data);
}
function checkFunc(id, action, checked) {
	var record = tree.getRecord(id);		//得到指定行
	if (!record)
		return;
	var funs = record.functions;
	if (!funs)
		return;
	function getAction(action) {
		for (var i = 0, l = funs.length; i < l; i++) {
			var o = funs[i];
			if (o.action == action)
				return o;
		}
	}
	var obj = getAction(action);
	if (!obj)
		return;
	obj.checked = checked;
}
//查询（角色）
function onFilterChanged(e) {
	var rcValue = mini.get("rcFilter").getValue().toLowerCase();
	var rnValue = mini.get("rnFilter").getValue().toLowerCase();
	var rdValue = mini.get("rdFilter").getValue().toLowerCase();
	grid.filter(function(row) {
		var r1 = true;
		if (rcValue) {
			r1 = String(row.roleCode).toLowerCase().indexOf(rcValue) != -1;
		}
		var r2 = true;
		if (rnValue) {
			r2 = String(row.roleCode).toLowerCase().indexOf(rnValue) != -1;
		}
		var r3 = true;
		if (rdValue) {
			r3 = String(row.roleCode).toLowerCase().indexOf(rdValue) != -1;
		}
		return r1 && r2 && r3;
	});
}

//数组去重
function uniq(array){
	var temp = [];
	for(var i = 0; i < array.length; i++) {
		//如果当前数组的第i项在当前数组中第一次出现的位置是i，才存入数组；否则代表是重复的
		if(array.indexOf(array[i]) == i){
			temp.push(array[i])
		}
	}
	return temp;
}
